import React from 'react';
import {
  List,
  Card,
  Drawer,
  Form,
  Button,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  InputNumber,
  Badge, Icon,
} from 'antd';
import PropTypes from 'prop-types';

const { TextArea } = Input;
const { Option } = Select;

class EditFormContent extends React.Component {
  state = { visible: false };

  constructor(props) {
    super(props);
  }


  fileRef = (obj) => {
    this.fileInput = obj;
  };

  openFileDialog = () => {
    this.fileInput.click();
  };


  onFileChange = (event) => {
    const form = this.props.form;
    if (event.target.files.length > 0) {
      const fileObj = event.target.files[0];
      const fileName = fileObj.name;
      const reader = new FileReader();
      reader.readAsArrayBuffer(fileObj);
      reader.onload = ((e) => {
        const buffer = e.target.result;
        const base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
        form.setFieldsValue({ PfxData: base64String, PfxFileName: fileName });
        form.resetFields(['upload']);
      });
    }
  };

  uploadValidator = (rule, value, cb) => {
    const form = this.props.form;
    const PfxData = form.getFieldValue('PfxData');
    const PfxFileName = form.getFieldValue('PfxFileName');
    if (PfxFileName && PfxData) {
      cb();
    } else {
      cb(false);
    }
  };

  downloadFile = () => {
    const form = this.props.form;
    const PfxData = form.getFieldValue('PfxData');
    const base64ToArrayBuffer = (base64) => {
      const binary_string = atob(base64);
      const len = binary_string.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
      }
      return bytes.buffer;
    };
    const blob = new Blob([base64ToArrayBuffer(PfxData)], { type: 'application/txt' });
    const objectUrl = URL.createObjectURL(blob);
    location.href = objectUrl;
  };

  renderFileName = () => {
    let fileName = undefined;
    if (this.fileInput && this.fileInput.files.length > 0) {
      const fileObj = this.fileInput.files[0];
      fileName = fileObj.name;
    } else {
      try {
        const parameters = JSON.parse(this.props.parameters);
        fileName = parameters.PfxFileName;
      } catch (e) {
      }
    }
    if (fileName) {
      return <a onClick={this.downloadFile.bind(this)}>{fileName}</a>;
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    let parameters = {};
    try {
      parameters = JSON.parse(this.props.parameters);
    } catch (e) {

    }
    const { FeeRate, MinFeeRate, CreditFeeRate, MerchantKey, RefundFee, PfxData, PfxFileName, CertPassword } = parameters;
    return (
      <Form layout="vertical" hideRequiredMark>
        <Row>
          <Form.Item label="渠道费率">
            {getFieldDecorator('FeeRate', {
              initialValue: FeeRate,
              rules: [{ required: true, message: '请填写渠道费率' }],

            })(<InputNumber placeholder="渠道费率" style={{ width: '150px' }}
                            min={0}
                            max={100}
                            formatter={value => `${value}%`}
                            parser={value => value.replace('%', '')}/>)}
            <div style={{
              color: '#ccc',
              padding: '4vm',
            }}>请在此处填写你的渠道签约费率，以便我们在报表中帮你计算结算金额。若不清楚签约费率，请联系支付渠道确认。（目前暂不支持阶梯费率计算）
            </div>
          </Form.Item>
        </Row>
        <Row>
          <Form.Item label="最低手续费">
            {getFieldDecorator('MinFeeRate', {
              initialValue: MinFeeRate,
              rules: [{ required: true, message: '请填写最低手续费' }],

            })(<InputNumber placeholder="最低手续费" style={{ width: '100%' }}
                            min={0}
                            max={100}
                            formatter={value => `${value}元`}
                            parser={value => value.replace('元', '')}/>)}
          </Form.Item>
        </Row>
        <Row>
          <Form.Item label="贷记卡费率">
            {getFieldDecorator('CreditFeeRate', {
              initialValue: CreditFeeRate,
              rules: [{ required: true, message: '请填写贷记卡费率' }],

            })(<InputNumber placeholder="贷记卡费率" style={{ width: '100%' }}
                            min={0}
                            max={100}
                            formatter={value => `${value}%`}
                            parser={value => value.replace('%', '')}/>)}
            <div style={{
              color: '#ccc',
              padding: '4vm',
            }}>若你与渠道签约费率区分借记卡和贷记卡，请在此处填写贷记卡手续费率。若签约手续费不区分借记卡和贷记卡则和渠道费率一样
            </div>
          </Form.Item>
        </Row>
        <Row>
          <Form.Item label="商户号">
            {getFieldDecorator('MerchantKey', {
              initialValue: MerchantKey,
              rules: [{ required: true, message: '请填写商户号' }],
            })(<Input placeholder="商户号"/>)}
          </Form.Item>
        </Row>
        <Row>
          <Form.Item
            label="Pfx文件上传(acp_sign.pfx)"
          >
            {getFieldDecorator('upload', {
              rules: [{
                validator: this.uploadValidator.bind(this), message: '请上传pfx文件',
              }],
            })(
              <div>
                <input type="file" ref={this.fileRef.bind(this)} onChange={this.onFileChange.bind(this)}
                       style={{ display: 'none' }}/>
                <Button onClick={this.openFileDialog.bind(this)}>
                  <Icon type="upload"/> 上传文件
                </Button>
                <div>
                  {this.renderFileName()}
                </div>
              </div>,
            )}
          </Form.Item>
          <div style={{ display: 'none' }}>
            <Form.Item>
              {getFieldDecorator('PfxData', {
                initialValue: PfxData,
              })(
                <Input/>,
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('PfxFileName', {
                initialValue: PfxFileName,
              })(
                <Input/>,
              )}
            </Form.Item></div>
        </Row>
        <Row>
          <Form.Item label="安全证书密码">
            {getFieldDecorator('CertPassword', {
              initialValue: CertPassword,
              rules: [{ required: true, message: '请填写安全证书密码' }],
            })(<Input placeholder="安全证书密码"/>)}
          </Form.Item>
        </Row>

        <Row>
          <Form.Item label="退款时是否退还支付手续费">
            {getFieldDecorator('RefundFee', {
              initialValue: RefundFee,
              rules: [{ required: true, message: '请选择退款时是否退还支付手续费' }],
            })(
              <Select placeholder="请选择退款时是否退还支付手续费">
                <Option value="1">是</Option>
                <Option value="0">否</Option>
              </Select>,
            )}
          </Form.Item>
        </Row>

      </Form>
    );
  }
}

const EditForm = Form.create()(EditFormContent);

EditForm.propTypes = {
  parameters: PropTypes.string.isRequired,

};
export default EditForm;
